package com.powernode.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.powernode.domain.SysMenu;
import com.powernode.service.SysMenuService;
import com.powernode.mapper.SysMenuMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 *
 */
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu>
        implements SysMenuService {
    @Autowired
    private SysMenuMapper sysMenuMapper;

    /**
     * 获取所有的菜单
     * 但是由于菜单分级 所有需要对菜单进行分级
     * 在实体类创建一个List
     *
     * @param sysUserId
     * @return
     */
    @Override
    public List<SysMenu> getMenusByUserId(Long sysUserId) {
        List<SysMenu> menuList = sysMenuMapper.getMenusByUserId(sysUserId);
        /**
         * 由于根据规律知道二级菜单的parent_id就是一级菜单的menu_id 以此类推
         */
        //定义一个递归方法

        return transMenuTree(menuList, 0l);
    }

    private List<SysMenu> transMenuTree(List<SysMenu> menuList, long pid) {
        //进行过滤查询到第一层的菜单
        List<SysMenu> menus = menuList.stream().filter(sysMenu -> sysMenu.getParentId().equals(pid)).collect(Collectors.toList());
        //在通过第一层进行调用此方法
        menus.forEach(p -> p.setList(transMenuTree(menuList, p.getMenuId())));
        return menus;
    }
}




